package cn.lb.org.controller;

import cn.lb.basic.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {



    @Value("D:\\img\\")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //截取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机名字
        String filename = UUID.randomUUID().toString()+suffix;
        //创建目录
        File dir=new File(basePath);
        //判断目录是否穿在，不纯在则创建
        if(!dir.exists()){
            dir.mkdirs();
        }
        //将上传的文件转纯在指定路径
        file.transferTo(new File(basePath+filename));
        return R.me().setData(basePath+filename);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //创建输入流
        FileInputStream fileInputStream=new FileInputStream(new File(basePath+name));
        //创建输出流
        ServletOutputStream outputStream= response.getOutputStream();
        response.setContentType("img/jpeg");
        //用输入流读取文件
        int len=0;
        byte[] bytes = new byte[1024];
        while((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭
        outputStream.close();
        fileInputStream.close();




    }
}
